package com.csdn.controller;

import com.csdn.dao.UserMapper;
import com.csdn.entity.CatContext;
import com.csdn.entity.User;
import com.csdn.excetion.GatewayExcetion;
import com.csdn.excetion.NEXTExcetion;
import com.csdn.excetion.RouteExcetion;
import com.csdn.service.CatService;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Transaction;

import com.dianping.cat.message.internal.DefaultTransaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/cat")
public class CatController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CatService catService;
    private final static Logger LOGGER = LoggerFactory.getLogger(CatController.class);

    @GetMapping("/log")
    public String Log() {
        userMapper.findAll();
        Cat.getManager().setTraceMode(true);
        LOGGER.info("cat info xxxxxxxxxzzz");
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            LOGGER.error("cat error  aaaaaaaaabbbbb", e);
        }
        test();
        return "Log";
    }

    //执行链路
    @GetMapping("/tran")
    public String hello() {
        Transaction t = Cat.newTransaction("URL-HELLO", "hello");
        t.setTimestamp(System.currentTimeMillis());
        t.addData(System.currentTimeMillis()+"");
        try {
            test();
            int i = 10 / 0;
            t.setStatus(Transaction.SUCCESS);

        } catch (Exception ex) {
            t.setStatus(ex);

            Cat.logError(ex);
            throw ex;
        } finally {
            t.complete();
        }
        return "cat transaction";
    }

    @GetMapping("/test1")
    public String xasd() {
        try {
            throw new RuntimeException("测试错误上报");
        } catch (Exception e) {
            Cat.logError(e);
        }
        return "xxxxx";
    }

    @GetMapping("/tes2")
    public String tes2() {
        try {
            throw new RouteExcetion("RouteExcetion,测试错误上报");
        } catch (Exception e) {
            Cat.logError(e);
        }
        return "tes2";
    }

    @GetMapping("/tes3")
    public String tes3() {
        Transaction t = Cat.newTransaction("URL", "TEST");
        try {
            if (1 == 1) {
                throw new GatewayExcetion("GatewayExcetion,测试错误上报");
            }
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception ex) {
            t.setStatus(ex);
            throw ex;
        } finally {
            t.complete();
        }

        return "tes3";
    }

    @GetMapping("/tes4")
    public String tes4() {
        Transaction t = Cat.newTransaction("URL", "TEST");
        try {
            if (1 == 1) {
                throw new NEXTExcetion("NEXTExcetion,测试错误上报");
            }
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception ex) {
            t.setStatus(ex);
            //throw ex;
        } finally {
            t.complete();
        }
        return "tes4";
    }

    @GetMapping("/tes5")
    public String tes5() {
        Transaction t = Cat.newTransaction("MXAKK", "TTTX");
        try {
            if (1 == 1) {
                throw new NEXTExcetion("NEXTExcetion,测试错误上报");
            }
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception ex) {
            t.setStatus(ex);
            //  LOGGER.error("xxx",ex);
            throw ex;
        } finally {
            t.complete();
        }
        return "tes5";
    }

    @GetMapping("/event")
    public String event() {
        Cat.logEvent("URL.ServerABBDB", "serverIp", Event.SUCCESS, "127.0.0.1");
        return "cat logEvent";
    }

    //统计访问次数
    @GetMapping("/metricCount")
    public String metricCount() {
        Cat.logMetricForCount("metricCount");
        return "metricCount";
    }

    //统计平均耗时
    @GetMapping("/duration")
    public String duration() {
        long start = System.currentTimeMillis();
        Random random = new Random();
        int randomNumber = random.nextInt(10) + 1;
        try {
            Thread.sleep(randomNumber * 1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long duration = System.currentTimeMillis() - start;
        Cat.logMetricForDuration("duration", duration);
        return "test";
    }

    private void test() {
        Transaction t = Cat.newTransaction("TEST", "test001");
        try {
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception ex) {
            t.setStatus(ex);
            Cat.logError(ex);
            throw ex;
        } finally {
            t.complete();
        }
    }

    @GetMapping("/sql")
    public List<User> sql() {
        Cat.getManager().setTraceMode(true);
        return userMapper.findAll();
    }

    @GetMapping("/testLog")
    public String testLog() {
        Transaction t = null;
        try {
            t = Cat.newTransaction("APass.Server", "1001");
            int a = 10 / 0;
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            t.setStatus(e);
            LOGGER.error("网关错误异常码[U20001]", e);
        } finally {
            t.complete();
        }
        return "hello world";
    }

    @GetMapping("/testLog2")
    public String testLog2() {
        Transaction t = Cat.newTransaction("UAUUAUUA", "XXXXXX");
        try {
            if (1 == 1) {
                throw new NEXTExcetion("NEXTExcetion,测试错误上报");
            }
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception ex) {
            LOGGER.error("网关错误异常码[999000]", ex);
            throw ex;
        } finally {
            t.complete();
        }
        return "hello world2";
    }

    @GetMapping("/chain")
    public String chain() {
        DefaultTransaction defaultTransaction = (DefaultTransaction) Cat.newTransaction("Test_Cat", "Cat.Controller2");
        String res = null;
        try {
            CatContext context = new CatContext();
            context.setMyTransaction(defaultTransaction);
            res = catService.hello(context);
        } catch (Exception e) {
            defaultTransaction.setStatus(e);
        } finally {
            defaultTransaction.complete();
        }
        return res;
    }


}
